package com.sita.cfmoto.interact.adapter;

import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.sita.cfmoto.R;
import com.sita.cfmoto.rest.model.Dynamic;
import com.sita.cfmoto.support.GlobalContext;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by lijuan zhang on 2016/8/4.
 */
public class OfficialSelectViewPagerAdapter extends PagerAdapter {
    private List<ImageView> data;
    private OnItemClickListener itemClickListener;
    private List<Dynamic> dynamics = new ArrayList<>();

    public OfficialSelectViewPagerAdapter(List<ImageView> data) {
        this.data = data;
    }

    public void setData(List<Dynamic> dynamics) {
        this.dynamics.clear();
        this.dynamics = dynamics;
        notifyDataSetChanged();
    }

    public void setOnItemClickListener(OnItemClickListener itemClickListener) {
        this.itemClickListener = itemClickListener;
    }

    @Override
    public int getCount() {
        return Integer.MAX_VALUE;
    }

    @Override
    public boolean isViewFromObject(View arg0, Object arg1) {
        return arg0 == arg1;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
    }

    /**
     * 载入图片进去，用当前的position 除以 图片数组长度取余数是关键
     */
    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        ImageView imageView = null;
        try {
            imageView = data.get(position % data.size());
            ((ViewPager) container).addView(imageView, 0);
        } catch (Exception e) {
        }
        if (dynamics.size() != 0 && imageView != null) {
            List<String> picList = dynamics.get(position % data.size()).picList;
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            Picasso.with(GlobalContext.getGlobalContext()).load(picList == null || picList.size() == 0 ? null : picList.get(0)).placeholder(R.drawable.official_dynamic_default_icon)
                    .into(imageView);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (itemClickListener != null)
                        itemClickListener.onItemClick(v, position % data.size(), dynamics.get(position % data.size()));
                }
            });
        }
        return data.get(position % data.size());
    }

    @Override
    public int getItemPosition(Object object) {
        return POSITION_NONE;
    }

    public interface OnItemClickListener {
        void onItemClick(View view, int position, Dynamic dynamic);
    }
}
